package com.ys.service.hr.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.TwlStock;
import com.ys.entity.hr.TwlStockIn;
import com.ys.entity.hr.TwlStockOut;
import com.ys.entity.hr.TwlStockOutDetail;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.hr.TwlStockChangeEnum;
import com.ys.enume.hr.TwlStockFrozenRunningEnum;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.TwlStockOutDetailMapper;
import com.ys.mapper.hr.TwlStockOutMapper;
import com.ys.service.flow.YspTaskService;
import com.ys.service.hr.TwlStockOutService;
import com.ys.service.hr.TwlStockService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("twlStockOutService")
public class TwlStockOutServiceImpl implements TwlStockOutService {

	@Autowired
	private HrMapper hrMapper;
	@Autowired
	private TwlStockOutMapper twlStockOutMapper;
	@Autowired
	private TwlStockOutDetailMapper twlStockOutDetailMapper;

	@Autowired
	private TwlStockService twlStockService;
	@Autowired
	private YspTaskService yspTaskService;
	
	/*
	 * 新增
	 */
	@Override
	public R add(String bid, String remark, String detailArr, Long menuId) throws Exception {
		
		if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		} else if(new TwlStockIn().setBid(bid).count() > 0) {
			return R.error("单号已存在");
		}
		
		/*
		 *  验证详情数据物料
		 *  1、编码不能为空
		 *  2、数量不能为空，且不能超过可用数量
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			TwlStock twlStock = new TwlStock().setId(stockId).queryFirst();
			if (num > twlStock.getNumAll()) {
				return R.error("【" + stockId + "】总数量不足");
			}
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		// 添加出库单
		TwlStockOut entity = null;
		{
			Integer effectStock = FlowEnum.EffectStock.NOT_EFFECT.value;
			Long createChangeId = tsUserChange.getId();
			entity = TwlStockOut.twlStockOut(bid, effectStock, createChangeId, remark, 1);
			twlStockOutMapper.insert(entity);
		}
		
		// 添加出库明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");
			if (stockId == null) {
				return R.error("库存ID不能为空");
			}

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			String bidStockOut = bid;
			TwlStockOutDetail twlStockOutDetail = TwlStockOutDetail.twlStockOutDetail(bidStockOut, stockId, num, remark, 1);
			twlStockOutDetailMapper.insert(twlStockOutDetail);
		}
		
		/*
		 * 流程初始化
		 */
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, bid, createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/hr/twlStockOut/toFlow?bid=" + bid));
	}
	
	@Override
	@Transactional
	public R edit(String bid, String remark, String detailArr, Long menuId) throws Exception {
		
		Integer stateFlow = yspTaskService.flowState(bid);
		if (stateFlow != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("非制单中数据，无法修改");
		}
		
		// 验证是否制单人
		YsProcInst entity = new YsProcInst().setBid(bid).queryFirst();
		if (!entity.getCreateUserId().equals(ShiroUtils.getUserId())) {
			return R.error("非制单人无法修改");
		}
		
		/*
		 *  验证详情数据物料
		 *  1、编码不能为空
		 *  2、数量不能为空，且不能超过可用数量
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			TwlStock twlStock = new TwlStock().setId(stockId).queryFirst();
			if (num > twlStock.getNumAll()) {
				return R.error("【" + stockId + "】总数量不足");
			}
		}
		
		// 删除旧的出库明细
		hrMapper.deleteTwlStockOutDetailByBid(bid);
		
		// 添加出库明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			
			String bidStockOut = bid;
			String remark2 = null;
			TwlStockOutDetail twlStockOutDetail = TwlStockOutDetail.twlStockOutDetail(bidStockOut, stockId, num, remark2, 1);
			twlStockOutDetailMapper.insert(twlStockOutDetail);
		}
		
		return R.ok(EditDto.reloadPage("/web/hr/twlStockOut/toFlow?bid=" + bid));
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		TwlStockOut entity = new TwlStockOut().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		
		if (!tsUserChange.getUserId().equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		
		// 删除主数据
		twlStockOutMapper.deleteTrue(id);
		
		// 删除子数据
		List<TwlStockOutDetail> listDetail = new TwlStockOutDetail().setBidStockOut(entity.getBid()).queryList();
		for(TwlStockOutDetail detail : listDetail) {
			twlStockOutDetailMapper.deleteTrue(detail.getId());
		}
		
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {
		
		TwlStockOut entity = new TwlStockOut().setId(id).queryFirst();
		String bid = entity.getBid();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		
		// 若流程是初始化状态，需要验证库存并冻结
		List<TwlStockOutDetail> listDetail = new TwlStockOutDetail().setBidStockOut(entity.getBid()).queryList();
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
			for(TwlStockOutDetail detail : listDetail) {
				Long stockId = detail.getStockId();
				Integer num = detail.getNum();
				
				TwlStock twlStock = new TwlStock().setId(stockId).queryFirst();
				if (num > twlStock.getNum()) {
					return R.error("【" + twlStock.getMaterialCode() + "】可用数量不足");
				}
			}
		}
		
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				// 若是制单流转，冻结账户
				if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
					for(TwlStockOutDetail detail : listDetail) {
						
						// 冻结库存
						Long stockId = detail.getStockId();
						Integer type = TwlStockFrozenRunningEnum.Type.FROZEN_OUT.value;
						String sourceBid = bid;
						Long sourceId = detail.getId();
						Integer frozenNum = detail.getNum();
						twlStockService.frozen(stockId, type, sourceBid, sourceId, frozenNum);
					}
				}
				
				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(id);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {
		
		TwlStockOut entity = new TwlStockOut().setId(id).queryFirst();
		String bid = entity.getBid();
		
		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
		
		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻库存
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				List<TwlStockOutDetail> listDetail = new TwlStockOutDetail().setBidStockOut(entity.getBid()).queryList();
				for(TwlStockOutDetail detail : listDetail) {
					
					// 解冻库存
					Long stockId = detail.getStockId();
					Integer type = TwlStockFrozenRunningEnum.Type.UNFROZEN_OUT.value;
					String sourceBid = bid;
					Long sourceId = detail.getId();
					Integer unfrozenNum = detail.getNum();
					twlStockService.unfrozen(stockId, type, sourceBid, sourceId, unfrozenNum);
				}
			}
		}
		return r;
	}


	@Override
	public R flowInit(Long id, String reason, String loginUserId) throws Exception {

		TwlStockOut entity = new TwlStockOut().setId(id).queryFirst();
		String bid = entity.getBid();

		R r = yspTaskService.flowInit(bid, reason, loginUserId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻库存
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				List<TwlStockOutDetail> listDetail = new TwlStockOutDetail().setBidStockOut(entity.getBid()).queryList();
				for(TwlStockOutDetail detail : listDetail) {

					// 解冻库存
					Long stockId = detail.getStockId();
					Integer type = TwlStockFrozenRunningEnum.Type.UNFROZEN_OUT.value;
					String sourceBid = bid;
					Long sourceId = detail.getId();
					Integer unfrozenNum = detail.getNum();
					twlStockService.unfrozen(stockId, type, sourceBid, sourceId, unfrozenNum);
				}
			}
		}
		return r;
	}

	@Override
	@Transactional
	public void flowFinish(Long id) throws Exception {
		
		TwlStockOut entity = new TwlStockOut().setId(id).queryFirst();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		twlStockOutMapper.update(entity);

		List<TwlStockOutDetail> listDetail = new TwlStockOutDetail().setBidStockOut(entity.getBid()).queryList();
		for(TwlStockOutDetail detail : listDetail) {
			
			// 解冻库存
			Long stockId = detail.getStockId();
			Integer type = TwlStockFrozenRunningEnum.Type.UNFROZEN_OUT.value;
			String sourceBid = entity.getBid();
			Long sourceId = detail.getId();
			Integer unfrozenNum = detail.getNum();
			twlStockService.unfrozen(stockId, type, sourceBid, sourceId, unfrozenNum);
			
			// 扣减库存
			Integer type2 = TwlStockChangeEnum.Type.OUT.value;
			Integer sourceNum = detail.getNum();
			twlStockService.change(stockId, type2, sourceId, sourceBid, sourceNum);
		}
	}

	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList(String bid) throws Exception{
		List<Map<String, Object>> sonlist = new TwlStockOutDetail()
				.setBidStockOut(bid)
				.addLeftJoin("TWL_Stock B on B.Id = A.StockId")
				.addField("B.Num stockNum")
				.addField("B.StockInDay stockInDay")
				.addField("DATEDIFF(DAY, B.StockInDay , getdate()) stockDays")
				.addField("B.Remark stockRemark")

				.addLeftJoin("TWL_StockInDetail B1 on B1.Id = B.StockInDetailId")
				.addField("B1.Img stockInImg")
				.addField("B1.Price stockInPrice")
				.addField("B1.BidStockIn bidStockIn")

				.addLeftJoin("TS_OrganizationInfo B2 on B2.Orgid = B.Orgid")
				.addField("B2.OrgName orgName")
				.addField("B2.HeadUserId orgHeadUserId")

				.addLeftJoin("TB_Material C on C.Code = B.MaterialCode")
				.addField("C.Code materialCode")
				.addField("C.Name materialName")
				.addField("C.Remark materialRemark")

				.addLeftJoin("TB_CompanyInfo D ON D.Vid = B.CompanyVid")
				.addField("D.Vname companyVname")
				.queryMap();
		return sonlist;
	}


}
